package com.youlu.campus.service.point.impl;

import com.mongodb.client.result.UpdateResult;

import com.youlu.campus.entity.UserPointTaskInfo;
import com.youlu.campus.service.point.UserPointTaskInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class UserPointTaskInfoServiceImpl implements UserPointTaskInfoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<UserPointTaskInfo> find(String userId, String appId, String platform) {
        Query query = new Query().addCriteria(Criteria.where("userId").is(userId).and("appId").is(appId).and("platform").is(platform));
        List<UserPointTaskInfo> datas = mongoTemplate.find(query, UserPointTaskInfo.class);
        return datas;
    }


    @Override
    public boolean create(@NotNull UserPointTaskInfo u) {
        u.setId(null);
        u.setCreatedTime(new Date());
        try {
            u = mongoTemplate.insert(u);
            if (StringUtils.isNotBlank(u.getId())) {
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error(":>>> 新增用户积分任务错误:{}", e);
            return false;
        }
    }

    @Override
    public boolean update(@NotNull UserPointTaskInfo u) {
        Query query = new Query().addCriteria(Criteria.where("id").is(u.getId()));
        Update update = new Update();
        Date date = new Date();
        boolean toUpdate = false;
        if (Objects.nonNull(u.getStatus())) {
            update.set("status", u.getStatus());
            toUpdate = true;
        }
        if (Objects.nonNull(u.getDoneTime())) {
            update.set("doneTime", u.getDoneTime());
            toUpdate = true;
        }
        if (Objects.nonNull(u.getQuantity())) {
            update.set("quantity", u.getQuantity());
            toUpdate = true;
        }
        if (toUpdate) {
            update.set("updatedTime", date);
            UpdateResult updateResult = mongoTemplate.updateFirst(query, update, UserPointTaskInfo.class);
            return updateResult.getModifiedCount() > 0 ? true : false;
        }
        return false;
    }
}
